
package com.xh.demo.datasource.config;

import com.xh.demo.datasource.ThreadLocalRouteDataSource;
import com.xh.demo.datasource.enums.DataSourceEnum;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Bean("dataSource1")
    @ConfigurationProperties(prefix = "spring.datasource1")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean("dataSource2")
    @ConfigurationProperties(prefix = "spring.datasource2")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public ThreadLocalRouteDataSource threadLocalRouteDataSource() {
        ThreadLocalRouteDataSource dataSource = new ThreadLocalRouteDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        DataSource master = dataSource1();  //默认数据源
        DataSource other = dataSource2();   //其他数据源
        targetDataSources.put(DataSourceEnum.MASTER.name(), master);
        targetDataSources.put(DataSourceEnum.OTHER.name(), other);
        // 设置数据源池的key和数据源的映射
        dataSource.setTargetDataSources(targetDataSources);
        // 把主数据源设置为默认数据源
        dataSource.setDefaultTargetDataSource(master);
        return dataSource;
    }

//    @Autowired
//    @Qualifier("jdbcTemplate2")
//    private JdbcTemplate jdbcTemplate;

//    @Bean
//    @Primary
//    public JdbcTemplate jdbcTemplate1(@Qualifier("dataSource1") DataSource dataSource) {
//        return new JdbcTemplate(dataSource);
//    }
//
//    @Bean(name = "jdbcTemplate2")
//    public JdbcTemplate jdbcTemplate2(@Qualifier("dataSource2") DataSource dataSource) {
//        return new JdbcTemplate(dataSource);
//    }

}
